package com.jic.market.impl.rest.seckill;


import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.manager.request.SysDeptRequest;
import com.jic.manager.response.MemStoreResponse;
import com.jic.market.entity.PromotionEntity;
import com.jic.market.entity.PromotionMemberGrade;
import com.jic.market.entity.PromotionMerchantProductEntity;
import com.jic.market.entity.base.BaseActivity;
import com.jic.market.entity.skill.ActivitySkillGoodsConfig;
import com.jic.market.entity.skill.SkillActivityTimeConfig;
import com.jic.market.enums.PromotionStatusEnum;
import com.jic.market.mapper.PromotionEntityMapper;
import com.jic.market.mapper.PromotionMemberGradeMapper;
import com.jic.market.mapper.PromotionMerchantProductEntityMapper;
import com.jic.market.mapper.base.BaseActivityMapper;
import com.jic.market.mapper.skill.ActivitySkillGoodsConfigMapper;
import com.jic.market.mapper.skill.SkillActivityTimeConfigMapper;
import com.jic.market.request.rest.seckill.*;
import com.jic.market.response.manager.product.GoodsSpuPageQueryResponse;
import com.jic.market.response.rest.SeckillInfoResponse;
import com.jic.market.response.rest.groupon.QueryGroupProductListResponse;
import com.jic.market.response.rest.seckill.QueryGoodsListResponse;
import com.jic.market.response.rest.seckill.SeckillTimeListResponse;
import com.jic.market.service.PromotionMemberGradeService;
import com.jic.market.service.rest.seckill.SeckillRestService;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.request.GoodsPageQueryRequest;
import com.jic.product.after.response.ProductStoreInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * H5 秒杀
 *
 * @author wwb
 */
@Slf4j
@Service
public class SeckillRestServiceImpl implements SeckillRestService {

    @Resource
    private SkillActivityTimeConfigMapper skillActivityTimeConfigMapper;

    @Resource
    private ActivitySkillGoodsConfigMapper activitySkillGoodsConfigMapper;

    @Resource
    private ProductListApi productListApi;

    @Autowired
    private PromotionMemberGradeService promotionMemberGradeService;

    @Autowired
    private PromotionMemberGradeMapper promotionMemberGradeMapper;

    @Autowired
    private PromotionEntityMapper promotionEntityMapper;

    @Resource
    private PromotionMerchantProductEntityMapper promotionMerchantProductEntityMapper;

    @Autowired
    private BaseActivityMapper baseActivityMapper;


    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");


    @Override
    public RestResult<List<SeckillTimeListResponse>> seckillTimeList(SeckillTimeListRequest request) {
        try {
            return RestResult.success(skillActivityTimeConfigMapper.queryDaySeckillTime());
        } catch (Exception e) {
            log.error("查询秒杀列表页失败=-=====><>>>>{}", e.getMessage());
            return RestResult.error("9999", "服务器错误, 请稍后...");
        }
    }

    @Override
    public RestResult<PageResult<QueryGoodsListResponse>> queryGoodsList(QueryGoodsListRequest queryGoodsListRequest) {
        try {
            queryGoodsListRequest.setStart((queryGoodsListRequest.getStart() - 1) * queryGoodsListRequest.getLimit());

            List<ActivitySkillGoodsConfig> activitySkillGoodsConfigList = activitySkillGoodsConfigMapper.queryGoodsInfoByTimeId(queryGoodsListRequest.getPromotionId(), queryGoodsListRequest.getTimeId(),
                    queryGoodsListRequest.getStart(), queryGoodsListRequest.getLimit());
            Long total = activitySkillGoodsConfigMapper.queryGoodsInfoByTimeIdTotal(queryGoodsListRequest.getPromotionId(), queryGoodsListRequest.getTimeId());

            //格式化 查询spu第三方编码
            List<Long> spuIds = activitySkillGoodsConfigList.stream().map(goodsConfig -> Long.valueOf(goodsConfig.getGoodsId())).collect(Collectors.toList());
            List<ProductStoreInfo> goodsSpuPageQueryResponses = productListApi.queryProductBySpuId(new GoodsPageQueryRequest() {{
                setSpuIds(spuIds);
            }});
//            List<GoodsSpuPageQueryResponse> goodsSpuPageQueryResponses = goodsSpuMapper.queryBySpuIds(spuIds);
            List<QueryGoodsListResponse> restList = new ArrayList<>();
            goodsSpuPageQueryResponses.forEach(item -> {
                QueryGoodsListResponse queryGoodsListResponse = new QueryGoodsListResponse();
                activitySkillGoodsConfigList.forEach(skillGoods -> {
                    if (item.getId().toString().equals(skillGoods.getGoodsId())) {
                        BigDecimal skillPrice = skillGoods.getSkillPrice();
//                        queryGoodsListResponse.setSkillPrice(skillPrice);
                    }
                });
//                queryGoodsListResponse.setThirdProductCode(item.getCode());

                // 过滤等级
                Boolean gradeFlag = Boolean.FALSE;
                if (StringUtils.isNotBlank(queryGoodsListRequest.getThirdUserId()) && StringUtils.isNotBlank(queryGoodsListRequest.getChannelCode())) {
                    PromotionEntity promotionEntity = promotionEntityMapper.queryByPromotionCode(queryGoodsListRequest.getPromotionId());
                    if (null != promotionEntity) {
                        PromotionMemberGrade promotionMemberGradeQ = new PromotionMemberGrade();
                        promotionMemberGradeQ.setPromotionCode(promotionEntity.getPromotionCode());
                        promotionMemberGradeQ.setDeleteFlag(false);
                        List<PromotionMemberGrade> promotionMemberGradeList = promotionMemberGradeMapper.query(promotionMemberGradeQ);
                        gradeFlag = promotionMemberGradeService.checkPromotion(queryGoodsListRequest.getThirdUserId(), queryGoodsListRequest.getChannelCode(), promotionEntity.getChannelCodes(), promotionMemberGradeList);
                    }
                }
                if (gradeFlag) {
                    restList.add(queryGoodsListResponse);
                }
            });
            return RestResult.success(new PageResult<QueryGoodsListResponse>() {{
                setTotal(total);
                setRows(restList);
            }});
        } catch (Exception e) {
            log.error("查询时间段下商品列表失败===<>>>>>>>>>>>>>{}", e.getMessage());
            return RestResult.error("9999", "服务器错误, 请稍后...");
        }
    }

    @Override
    public RestResult<PageResult<QueryGoodsListResponse>> queryProcessingGoodsListPage(QueryProcessingGoodsListPageRequest request) {
        try {
            request.setStart((request.getStart() - 1) * request.getLimit());
            //查询进行中的时间段
            List<SkillActivityTimeConfig> skillActivityTimeConfigs = skillActivityTimeConfigMapper.queryProcessingTimeList();

            List<String> skillTimeIdList = new ArrayList<>();
            for (SkillActivityTimeConfig skillActivityTimeConfig : skillActivityTimeConfigs) {
//                Boolean endStatus = checkLessTime(skillActivityTimeConfig.getStartTimeOfDate());
//                Boolean startStatus = checkMoreTime(skillActivityTimeConfig.getEndTimeOfDate());
//                if (startStatus && endStatus) {
                skillTimeIdList.add(skillActivityTimeConfig.getTimeId());
//                }
            }
            List<QueryGoodsListResponse> restList = skillActivityTimeConfigMapper.queryProcessingGoodsListPage(request, StringUtils.join(skillTimeIdList, ","));

            List<String> mpCodeList = restList.stream().map(QueryGoodsListResponse::getMpCode).collect(Collectors.toList());

            //格式化商品信息
            List<ProductStoreInfo> productStoreInfos = productListApi.queryProductListByThirdProductCodes(new GoodsPageQueryRequest() {{
                setThirdProductCodes(mpCodeList);
            }});

            restList.stream().forEach(item -> {
                List<ProductStoreInfo> productStoreInfo = productStoreInfos.stream().filter(product -> product.getId().equals(item.getMpId())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(productStoreInfo)) {
                    item.setPicUrl(productStoreInfo.get(0).getPictureUrl());
                    item.setSalePriceWithTax(productStoreInfo.get(0).getSalePriceWithTax());
                }
                item.setStatus("1");
            });

            Long total = skillActivityTimeConfigMapper.queryProcessingGoodsListPageCount(StringUtils.join(skillTimeIdList, ","));
            return RestResult.success(new PageResult<QueryGoodsListResponse>() {{
                setRows(restList);
                setTotal(total);
            }});
        } catch (Exception e) {
            log.error("查询进行中的商品失败===>>>>>>>>>>>", e);
            return RestResult.error("9999", "服务器错误, 请稍后...");
        }
    }


    @Override
    public RestResult<Boolean> checkSeckillProduct(CheckSeckillRequest request) {
        try {
            //查询活动是否正在进行中
            BaseActivity promotionEntity = baseActivityMapper.queryByPrimaryKey(Long.valueOf(request.getPromotionId()));
//            PromotionEntity promotionEntity = promotionEntityMapper.queryByPromotionCode(request.getPromotionId());
            if (promotionEntity == null) {
                return RestResult.error("9999", "活动不存在");
            }
            if (promotionEntity.getStatus().equals(PromotionStatusEnum.AUDIT_PASS.getCode())
                    && System.currentTimeMillis() >= promotionEntity.getStartTime().getTime()
                    && System.currentTimeMillis() <= promotionEntity.getEndTime().getTime()) {

                //查询时间段
                List<SkillActivityTimeConfig> timeIds = skillActivityTimeConfigMapper.query(new SkillActivityTimeConfig() {{
                    setTimeId(request.getTimeId());
                }});

                if (CollectionUtils.isEmpty(timeIds)) {
                    return RestResult.error("9999", "时间段不存在");
                }

                SkillActivityTimeConfig skillActivityTimeConfig = timeIds.get(0);
                Boolean endStatus = checkLessTime(skillActivityTimeConfig.getStartTimeOfDate());
                Boolean startStatus = checkMoreTime(skillActivityTimeConfig.getEndTimeOfDate());
                if (!startStatus || !endStatus) {
                    return RestResult.error("9999", "当前时间段不在进行");
                }
                Integer productCount = promotionMerchantProductEntityMapper.queryEntityByPromotionIdAndMpIdAndSkillTimeId(promotionEntity.getId(), request.getMpId(), request.getTimeId());
                if (productCount < 1) {
                    return RestResult.error("9999", "当前商品不在进行");
                }
            } else {
                return RestResult.error("9999", "当前秒杀活动不在进行");
            }
        } catch (Exception e) {
            log.error("checkSeckillProduct ======  error =====>>>>>>", e);
            return RestResult.error("9999", "服务器错误, 请稍后...");
        }
        return RestResult.success(true);
    }

    @Override
    public RestResult<PageResult<QueryGoodsListResponse>> queryAboutStartGoodsListPage(QueryProcessingGoodsListPageRequest request) {
        try {
            request.setStart((request.getStart() - 1) * request.getLimit());
            //查询进行中的时间段
            List<SkillActivityTimeConfig> skillActivityTimeConfigs = skillActivityTimeConfigMapper.queryNoStartTimeList();

            List<String> skillTimeIdList = new ArrayList<>();
            for (SkillActivityTimeConfig skillActivityTimeConfig : skillActivityTimeConfigs) {
                /*Boolean endStatus = checkMoreTime(skillActivityTimeConfig.getStartTimeOfDate());
                Boolean startStatus = checkMoreTime(skillActivityTimeConfig.getEndTimeOfDate());
                if (startStatus && endStatus) {
                    skillTimeIdList.add(skillActivityTimeConfig.getTimeId());
                }*/
                skillTimeIdList.add(skillActivityTimeConfig.getTimeId());
            }
            List<QueryGoodsListResponse> restList = skillActivityTimeConfigMapper.queryProcessingGoodsListPage(request, StringUtils.join(skillTimeIdList, ","));

            List<String> mpCodeList = restList.stream().map(QueryGoodsListResponse::getMpCode).collect(Collectors.toList());

            //格式化商品信息
            List<ProductStoreInfo> productStoreInfos = productListApi.queryProductListByThirdProductCodes(new GoodsPageQueryRequest() {{
                setThirdProductCodes(mpCodeList);
            }});

            restList.stream().forEach(item -> {
                List<ProductStoreInfo> productStoreInfo = productStoreInfos.stream().filter(product -> product.getId().equals(item.getMpId())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(productStoreInfo)) {
                    item.setPicUrl(productStoreInfo.get(0).getPictureUrl());
                    item.setSalePriceWithTax(productStoreInfo.get(0).getSalePriceWithTax());
                }
                item.setStatus("2");
            });

            Long total = skillActivityTimeConfigMapper.queryProcessingGoodsListPageCount(StringUtils.join(skillTimeIdList, ","));
            return RestResult.success(new PageResult<QueryGoodsListResponse>() {{
                setRows(restList);
                setTotal(total);
            }});
        } catch (Exception e) {
            log.error("查询进行中的商品失败===>>>>>>>>>>>", e);
            return RestResult.error("9999", "服务器错误, 请稍后...");
        }
    }

    @Override
    public RestResult<PageResult<QueryGoodsListResponse>> queryHasNotStartGoodsListPage(QueryProcessingGoodsListPageRequest request) {
        try {
            request.setStart((request.getStart() - 1) * request.getLimit());

            List<QueryGoodsListResponse> restList = skillActivityTimeConfigMapper.queryProcessingGoodsListPage(request, request.getTimeId());

            List<String> mpCodeList = restList.stream().map(QueryGoodsListResponse::getMpCode).collect(Collectors.toList());

            //格式化商品信息
            List<ProductStoreInfo> productStoreInfos = productListApi.queryProductListByThirdProductCodes(new GoodsPageQueryRequest() {{
                setThirdProductCodes(mpCodeList);
            }});

            restList.stream().forEach(item -> {
                List<ProductStoreInfo> productStoreInfo = productStoreInfos.stream().filter(product -> product.getId().equals(item.getMpId())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(productStoreInfo)) {
                    item.setPicUrl(productStoreInfo.get(0).getPictureUrl());
                    item.setSalePriceWithTax(productStoreInfo.get(0).getSalePriceWithTax());
                }

            });

            Long total = skillActivityTimeConfigMapper.queryProcessingGoodsListPageCount(request.getTimeId());
            return RestResult.success(new PageResult<QueryGoodsListResponse>() {{
                setRows(restList);
                setTotal(total);
            }});
        } catch (Exception e) {
            log.error("查询进行中的商品失败===>>>>>>>>>>>", e);
            return RestResult.error("9999", "服务器错误, 请稍后...");
        }
    }

    @Override
    public RestResult<SeckillInfoResponse> getSecondsKillInfo(SeckillInfoRequest seckillInfoRequest) {
        SeckillInfoResponse seckillInfoResponse = new SeckillInfoResponse();
        PromotionMerchantProductEntity promotionMerchantProductEntity =
                promotionMerchantProductEntityMapper.queryEntityByPromotionIdAndMpId(seckillInfoRequest.getPromotionId(), seckillInfoRequest.getGoodsId());
        if (promotionMerchantProductEntity != null) {
            SkillActivityTimeConfig skillActivityTimeConfig = skillActivityTimeConfigMapper.
                    queryTimeConfigByPromotionIdAndTimeId(String.valueOf(promotionMerchantProductEntity.getPromotionId()), promotionMerchantProductEntity.getSkillTimeId());
            if (skillActivityTimeConfig != null) {
                seckillInfoResponse.setPromPrice(promotionMerchantProductEntity.getPromPrice());
                seckillInfoResponse.setStartTime(skillActivityTimeConfig.getStartTimeOfDate());
                seckillInfoResponse.setEndTime(skillActivityTimeConfig.getEndTimeOfDate());
                seckillInfoResponse.setTimeId(skillActivityTimeConfig.getTimeId());
            }
        }
        return RestResult.success(seckillInfoResponse);
    }

    /**
     * 查询时间段数据
     *
     * @return
     */
    @Override
    public RestResult<List<SeckillTimeListResponse>> queryPeriodOfTime() {
        List<SeckillTimeListResponse> seckillTimeListResponses = new ArrayList<>();
        //查询进行中的时间段
        List<SkillActivityTimeConfig> skillActivityTimeConfigs = skillActivityTimeConfigMapper.queryEndTimeList();
        skillActivityTimeConfigs.forEach(item -> {
            SeckillTimeListResponse seckillTimeListResponse = new SeckillTimeListResponse();
            seckillTimeListResponse.setEndTimeOfDate(item.getEndTimeOfDate());
            seckillTimeListResponse.setStartTimeOfDate(item.getStartTimeOfDate());
            seckillTimeListResponse.setTimeId(item.getTimeId());
            try {
                Boolean endStatus = checkLessTime(item.getStartTimeOfDate());
                Boolean startStatus = checkMoreTime(item.getEndTimeOfDate());
                log.info("endStatus:{}",endStatus);
                log.info("startStatus:{}",startStatus);
                seckillTimeListResponse.setTimeState(1);
                if (startStatus && endStatus) {
                    seckillTimeListResponse.setTimeState(2);
                }
            } catch (ParseException e) {
                log.error("查询时间段数据:{}", e);
            }
            seckillTimeListResponses.add(seckillTimeListResponse);
        });
        return RestResult.success(seckillTimeListResponses);
    }

    /**
     * 小于等于
     *
     * @param time
     * @return
     * @throws ParseException
     */
    private Boolean checkLessTime(String time) throws ParseException {
        Date parse = sdf.parse(time);
        log.info("入参===>>{}", parse);
        Date date = new Date();
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String format = sdf2.format(date);
        log.info(format);
        String newTime = format.split(" ")[1];
        log.info("time=-====>>{}", newTime);
        Date parse1 = sdf.parse(newTime);
        log.info("data2=>>>{}", parse1);
        if (parse.getTime() <= parse1.getTime()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 大于等于
     *
     * @param time
     * @return
     * @throws ParseException
     */
    private Boolean checkMoreTime(String time) throws ParseException {
        Date parse = sdf.parse(time);
        log.info("入参===>>{}", parse);
        Date date = new Date();
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String format = sdf2.format(date);
        log.info(format);
        String newTime = format.split(" ")[1];
        log.info("time=-====>>{}", newTime);
        Date parse1 = sdf.parse(newTime);
        log.info("data2=>>>{}", parse1);
        if (parse.getTime() >= parse1.getTime()) {
            return true;
        } else {
            return false;
        }
    }
}


























